package com.example.practice.controller;

import com.example.practice.entity.Like;
import com.example.practice.repository.LikeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/likes")
public class LikeController {

    @Autowired
    private LikeRepository likeRepository;

    /**
     * 获取用户点赞的猫咪图片
     * @param username 用户名
     * @return 点赞的猫咪图片URL列表
     */
    @GetMapping
    public ResponseEntity<List<String>> getUserLikes(@RequestParam String username) {
        try {
            List<Like> likes = likeRepository.findByUsername(username);
            List<String> catUrls = likes.stream()
                    .map(Like::getCatUrl)
                    .collect(Collectors.toList());
            return ResponseEntity.ok(catUrls);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 添加点赞
     * @param username 用户名
     * @param request 包含猫咪图片URL的请求体
     */
    @PostMapping
    public ResponseEntity<Void> addLike(@RequestParam String username, @RequestBody LikeRequest request) {
        try {
            // 检查是否已经点赞过
            if (likeRepository.existsByUsernameAndCatUrl(username, request.getCatUrl())) {
                return ResponseEntity.badRequest().build();
            }
            
            Like like = new Like(username, request.getCatUrl());
            // 设置默认的userId和catId（从catUrl中提取catId）
            like.setUserId(1L); // 默认使用用户ID 1（YOAN账号）
            like.setCatId(extractCatIdFromUrl(request.getCatUrl()));
            likeRepository.save(like);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 取消点赞
     * @param username 用户名
     * @param catUrl 猫咪图片URL
     */
    @DeleteMapping
    public ResponseEntity<Void> removeLike(@RequestParam String username, @RequestParam String catUrl) {
        try {
            likeRepository.deleteByUsernameAndCatUrl(username, catUrl);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 检查用户是否点赞了某个猫咪图片
     * @param username 用户名
     * @param catUrl 猫咪图片URL
     * @return 是否已点赞
     */
    @GetMapping("/check")
    public ResponseEntity<Boolean> checkLike(@RequestParam String username, @RequestParam String catUrl) {
        try {
            boolean isLiked = likeRepository.existsByUsernameAndCatUrl(username, catUrl);
            return ResponseEntity.ok(isLiked);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }

    // 点赞请求的内部类
    static class LikeRequest {
        private String catUrl;

        public String getCatUrl() {
            return catUrl;
        }

        public void setCatUrl(String catUrl) {
            this.catUrl = catUrl;
        }
    }
    
    /**
     * 从猫咪图片URL中提取catId
     * @param catUrl 猫咪图片URL
     * @return 提取的catId
     */
    private String extractCatIdFromUrl(String catUrl) {
        try {
            // 从URL中提取文件名（不含扩展名）作为catId
            String[] parts = catUrl.split("/");
            String fileName = parts[parts.length - 1];
            return fileName.substring(0, fileName.lastIndexOf('.'));
        } catch (Exception e) {
            return "unknown";
        }
    }
}